package com.dhecp.project.logstics.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.framework.web.service.BaseInfoSimpleService;
import com.dhecp.project.base.domain.BaseInfo;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.logstics.domain.FbaSpellTicket;
import com.dhecp.project.logstics.domain.FbaSpellTicketDetail;
import com.dhecp.project.logstics.service.FbaSpellTicketDetailService;
import com.dhecp.project.logstics.service.FbaSpellTicketService;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 物流拼票 控制层
 * @author: fxz
 * @create: 2023-05-15 15:13
 */
@Controller
@RequestMapping("/logstics/fbaSpellTicket")
public class FbaSpellTicketController extends BaseModuleController {

    private String prefix = "logstics/fbaSpellTicket";
    private String moduleTable = ModuleTable.FBA_SPELLTICKET;
    private String moduleTable2 = ModuleTable.FBA_SPELLTICKET_DETAIL;

    @Autowired
    private FbaSpellTicketService fbaSpellTicketService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    @Autowired
    private FbaSpellTicketDetailService fbaSpellTicketDetailService;

    @Autowired
    private BaseInfoSimpleService baseInfoSimpleService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;


    /**
     * @Description: 打开查询列表页
     * @Param: [params]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: fxz
     * @date: 2023-05-15 15:42
     */
    @RequiresPermissions("logstics:fbaSpellTicket:view")
    @GetMapping()
    public ModelAndView view(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new FbaSpellTicket()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/fbaSpellTicket"); //页面路径
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");

        ModelAndView mv = this.openListPage(params);
        mv.addObject("logstics", "fbaSpellTicket");
        return mv;
    }


    /**
     * @Description: 查询页 列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: fxz
     * @date: 2023-05-15 15:42
     */
    @RequiresPermissions("logstics:fbaSpellTicket:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        List<FbaSpellTicket> list = new ArrayList<FbaSpellTicket>();
        try {
            list = fbaSpellTicketService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 查询页 子列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: fxz
     * @date: 2023-05-15 15:42
     */
    @RequiresPermissions("logstics:fbaSpellTicket:list")
    @GetMapping("/sonlist")
    @ResponseBody
    public AjaxResult sonlist(@RequestParam Map<String, Object> params) {

        try {
            AjaxResult ajaxResult = new AjaxResult();
            Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
            Map<String, Object> mapList = new HashMap<>();
            Map<String, Object> stringObjectMap = new HashMap<>();
            params.put("toolBarWidth", 0);
            params.put("moduleTable", moduleTable2);
            params.put("entity", new FbaSpellTicketDetail()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
            params.put("codeBox",params.get("code"));
            params.remove("code");
            if (params.get("creationMethod").equals("手动")){
                mapList.put("sonList", fbaSpellTicketDetailService.queryList(params));
            } else {
                mapList.put("sonList", fbaSpellTicketDetailService.queryAutoList(params));
            }
            stringObjectMap = gridColumnsPropertyModel.queryGridColumnsPropertyModel(params);
            mapList.put("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            mapList.put("gridColumns", stringObjectMap);
            ajaxResult = AjaxResult.success(mapList);
            return ajaxResult;
        } catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }

    /**
     * 打开物流名称新增页
     *
     * @Author: fxz
     * @date: 2022-09-21 11:41
     */
    @RequiresPermissions("logstics:fbaSpellTicket:add")
    @GetMapping("/add")
    public ModelAndView add(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new FbaSpellTicket()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
        List<Object> fieldsList = new ArrayList<Object>();            //生成控件的字段和属性
        List<Object> fieldsHiddenList = new ArrayList<Object>();    //隐藏的字段和属性
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        try {
            //查询数据字典
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()) {
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            } else {
                ajaxResult = AjaxResult.success("数据获取成功。");
            }

            params.put("getFieldAttributesType", "pagenotingrid");    //非表格字段
            dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
            FbaSpellTicket fbaSpellTicket = new FbaSpellTicket();
            if (dicFieldsList.isEmpty()) {
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            } else {
                fbaSpellTicket.setIsDeliver(0);
                for (SysDictionaryForPageField dicFields : dicFieldsList) {
                    Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                    fieldsListMap.put("fieldContent", TypeUtils.entityToMap(fbaSpellTicket).get(fieldsListMap.get("fields")));

                     if (fieldsListMap.get("fieldFrontType") == null) {
                        fieldsListMap.put("fieldFrontType", "t_text");
                    }
                    if (fieldsListMap.get("fieldContent") == null) {
                        fieldsListMap.put("fieldContent", "");
                    }

                    //如果有下拉控件，则根据配置获取对应下拉待选内容
                    List<BaseInfo> dropdownList = new ArrayList<BaseInfo>();
                    String fieldFrontType = dicFields.getFieldFrontType();
                    String fieldSearchType = dicFields.getFieldSearchType();
                    String fieldFrontSave = dicFields.getFieldFrontSave();
                    String fieldFrontShow = dicFields.getFieldFrontShow();
                    if (fieldFrontType != null && fieldFrontType.toLowerCase().startsWith("t_dropdown")) {
                        if (fieldSearchType != null && !"".equals(fieldSearchType)) {
                            if (fieldFrontSave == null || "".equals(fieldFrontSave)) {
                                fieldFrontSave = "vid";
                            }
                            if (fieldFrontShow == null || "".equals(fieldFrontShow)) {
                                fieldFrontShow = "vname";
                            }
                            dropdownList = baseInfoSimpleService.getDropdownData(fieldSearchType, fieldFrontSave, fieldFrontShow);
                        }
                    }
                    fieldsListMap.put("dropdownList", dropdownList);
                    if ((Integer) fieldsListMap.get("fieldFrontTop") == 1) {    //显示的字段
                        fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                    } else {    //隐藏的字段
                        fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                    }
                }
            }
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("guidList",  params.get("guidList"));
        mv.addObject("type",  params.get("type"));
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        params.put("entity", new FbaSpellTicket());
        params.put("toolBarWidth", 0);//操作
//        params.put("checkBox", "yes");
        params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段// 区
        Map<String, Object> stringObjectMap = gridColumnsPropertyModel.queryGridColumnsPropertyModel(params);
        mv.addObject("stringObjectMap", stringObjectMap);
        mv.addObject("enableEdit", 1); //当前页面是否可编辑（0：不可编辑，1：可编辑）
        mv.addObject("pageType", "add"); //页面类型：新增（add）、修改（edit）
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap)); //各字段及属性
        mv.addObject("fieldsList", fieldsList);                //显示的字段
        mv.addObject("fieldsHiddenList", fieldsHiddenList);    //隐藏的字段
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/fbaSpellTicket_edit");
        return mv;
    }

    @RequiresPermissions("logstics:fbaSpellTicket:add")
    @GetMapping("/details")
    @ResponseBody
    public TableDataInfo details(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        List<FbaSpellTicket> list = new ArrayList<FbaSpellTicket>();
        try {
            if (params.get("type").equals("0") || params.get("type").equals("2")){
                String guidList = String.valueOf(params.get("guidList"));
                String[] guidListSplit = guidList.split(",");
                params.put("guidListSplit",guidListSplit);
                list = fbaSpellTicketService.queryList(params);
            }else {
                list = fbaSpellTicketService.queryListMerge(params);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 保存数据
     * @Param: infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-08-15 15:44
     */
    @RequiresPermissions(value = {"logstics:fbaSpellTicket:add", "logstics:fbaSpellTicket:edit", "logstics:fbaSpellTicket:delete"}, logical = Logical.OR)
    @Log(title = "物流拼票单", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editpost(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            if (params.get("type").equals("0")){
                ajaxResult = fbaSpellTicketService.noTicket(params);
            }else  if (params.get("type").equals("1")){
                ajaxResult = fbaSpellTicketService.saveData(params);
            } else if (params.get("type").equals("2")){
                ajaxResult = fbaSpellTicketService.loadDelivery(params);
            }
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     * @Description: 回退
     * @Param: infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: fxz
     * @date: 2023-05-25 15:44
     */
    @RequiresPermissions(value = {"logstics:fbaSpellTicket:add"}, logical = Logical.OR)
    @Log(title = "物流拼票回退", businessType = BusinessType.UPDATE)
    @PostMapping("/htbtn")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult htbtn(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = fbaSpellTicketService.htbtn(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 拼票预测
     * @param request
     * @return
     */
    @RequestMapping("/ticketPooling")
    public ModelAndView toYys(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        try {
            ModelAndView mv = new ModelAndView();
            Map<String, Object> params3 = new HashMap<String, Object>();
            params3.put("guidList",request.getParameter("guidList"));
            mv.addObject("infoMap", fbaSpellTicketService.queryTicketPooling(params3));//母件数据
            mv.addObject("infoItems", fbaSpellTicketService.queryTicketPoolingDetail(params3));//子件数据
            mv.setViewName(prefix + "/ticketPooling");
            return mv;
        } catch (Exception e) {
            e.printStackTrace();
            return null;    //详细信息
        }
    }
}